using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System.IO;

using DotNetNuke.UI.Utilities;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Definitions;
using DotNetNuke.Application;
using DotNetNuke.Entities.Host;
using DotNetNuke.UI.Skins;
using DotNetNuke.Web.UI;

using Telerik.Web.UI;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Localization;
using DotNetNuke.Entities.Portals;

namespace DotNetNuke.UI.ControlPanel
{

	partial class UpdatePage : System.Web.UI.UserControl, DotNetNuke.Web.UI.WebControls.IDnnRibbonBarTool
	{

		#region "Event Handlers"


		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			cmdUpdate.Click += new EventHandler(cmdUpdate_Click);

			try
			{
				if (Visible && !IsPostBack)
				{
					Name.Text = CurrentTab.TabName;
					IncludeInMenu.Checked = CurrentTab.IsVisible;
					IsDisabled.Checked = CurrentTab.DisableLink;
					TRSSL.Visible = PortalSettings.SSLEnabled;
					IsSecure.Enabled = PortalSettings.SSLEnabled;
					IsSecure.Checked = CurrentTab.IsSecure;
					LoadAllLists();
				}
				//Module failed to load
			}
			catch (Exception exc)
			{
				DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
		}

		protected void cmdUpdate_Click(object sender, System.EventArgs e)
		{
			if ((TabPermissionController.CanManagePage()))
			{
				TabController tabCtrl = new TabController();

				int selectedTabID = Null.NullInteger;
				DotNetNuke.Entities.Tabs.TabInfo selectedTab = null;
				if ((!string.IsNullOrEmpty(PageLst.SelectedValue)))
				{
					selectedTabID = Int32.Parse(PageLst.SelectedValue);
					selectedTab = tabCtrl.GetTab(selectedTabID, PortalSettings.ActiveTab.PortalID, false);
				}

				TabRelativeLocation tabLocation = TabRelativeLocation.NOTSET;
				if ((!string.IsNullOrEmpty(LocationLst.SelectedValue)))
				{
					tabLocation = (TabRelativeLocation)Enum.Parse(typeof(TabRelativeLocation), LocationLst.SelectedValue);
				}

				DotNetNuke.Entities.Tabs.TabInfo tab = CurrentTab;

				tab.TabName = Name.Text;
				tab.IsVisible = IncludeInMenu.Checked;
				tab.DisableLink = IsDisabled.Checked;
				tab.IsSecure = IsSecure.Checked;
				tab.SkinSrc = SkinLst.SelectedValue;

				string errMsg = "";
				try
				{
					RibbonBarManager.SaveTabInfoObject(tab, selectedTab, tabLocation, null);
				}
				catch (DotNetNukeException ex)
				{
					DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
					if ((ex.ErrorCode != DotNetNukeErrorCode.NotSet))
					{
						errMsg = GetString("Err." + ex.ErrorCode.ToString());
					}
					else
					{
						errMsg = ex.Message;
					}
				}
				catch (Exception ex)
				{
					DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
					errMsg = ex.Message;
				}

				//Clear the Tab's Cached modules
				DotNetNuke.Common.Utilities.DataCache.ClearModuleCache(PortalSettings.ActiveTab.TabID);

				//Update Cached Tabs as TabPath may be needed before cache is cleared
				DotNetNuke.Entities.Tabs.TabInfo tempTab = null;
				if (new TabController().GetTabsByPortal(PortalSettings.ActiveTab.PortalID).TryGetValue(tab.TabID, out tempTab))
				{
					tempTab.TabPath = tab.TabPath;
				}

				if ((string.IsNullOrEmpty(errMsg)))
				{
					Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(tab.TabID));
				}
				else
				{
					//Show error
					errMsg = GetString("Err.Header") + "<br /><br />" + errMsg;
					errMsg = errMsg.Replace("\"", "'");
					Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "AddTabError", "function pageLoad() { radalert(\"" + errMsg + "\"); }", true);
					//DotNetNuke.Framework.jQuery.RequestRegistration()
					//Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "AddTabError", "jQuery(document).ready(function() { alert(""" + errMsg.Replace("""", "'") + """); });", True)
				}
			}
		}

		#endregion

		#region "Properties"

		public string ToolName
		{
			get { return "QuickUpdatePage"; }
			set
			{
				throw new NotSupportedException("Set ToolName not supported");
			}
		}

		public override bool Visible
		{
			get { return base.Visible == true && TabPermissionController.CanManagePage(); }
			set { base.Visible = value; }
		}

		#endregion

		#region "Methods"

		private void LoadAllLists()
		{
			LocationLst.Enabled = RibbonBarManager.CanMovePage();
			PageLst.Enabled = RibbonBarManager.CanMovePage();
			if ((LocationLst.Enabled))
			{
				LoadLocationList();
				LoadPageList();
			}

			LoadSkinList();
		}

		private void LoadSkinList()
		{
			SkinLst.ClearSelection();
			SkinLst.Items.Clear();
			SkinLst.Items.Add(new RadComboBoxItem(GetString("DefaultSkin"), ""));

			// load portal skins
			RadComboBoxItem portalSkinsHeader = new RadComboBoxItem(GetString("PortalSkins"), "");
			portalSkinsHeader.Enabled = false;
			portalSkinsHeader.CssClass = "SkinListHeader";
			SkinLst.Items.Add(portalSkinsHeader);

			string[] arrFolders = null;
			string[] arrFiles = null;
			string strLastFolder = "";
			string strRoot = PortalSettings.HomeDirectoryMapPath + SkinController.RootSkin;
			if (Directory.Exists(strRoot))
			{
				arrFolders = Directory.GetDirectories(strRoot);
				foreach (string strFolder in arrFolders)
				{
					arrFiles = Directory.GetFiles(strFolder, "*.ascx");
					foreach (string strFile in arrFiles)
					{
						string folder = strFolder.Substring(strFolder.LastIndexOf("\\") + 1);
						if (strLastFolder != folder)
						{
							if (!string.IsNullOrEmpty(strLastFolder))
							{
								SkinLst.Items.Add(GetSeparatorItem());
								//cboSkin.Items.Add(New ListItem(separatorText, ""))
							}
							strLastFolder = folder;
						}
						//cboSkin.Items.Add(New ListItem(FormatSkinName(strFolder, Path.GetFileNameWithoutExtension(strFile)), "[L]" & SkinRoot & "/" & strFolder & "/" & Path.GetFileName(strFile)))
						SkinLst.Items.Add(new RadComboBoxItem(FormatSkinName(folder, Path.GetFileNameWithoutExtension(strFile)), "[L]" + SkinController.RootSkin + "/" + folder + "/" + Path.GetFileName(strFile)));
					}
				}
			}

			//No portal skins added, remove the header
			if ((SkinLst.Items.Count == 2))
			{
				SkinLst.Items.Remove(1);
			}

			//load host skins
			RadComboBoxItem hostSkinsHeader = new RadComboBoxItem(GetString("HostSkins"), "");
			hostSkinsHeader.Enabled = false;
			hostSkinsHeader.CssClass = "SkinListHeader";
			SkinLst.Items.Add(hostSkinsHeader);

			strRoot = Common.Globals.HostMapPath + SkinController.RootSkin;
			if (Directory.Exists(strRoot))
			{
				arrFolders = Directory.GetDirectories(strRoot);
				foreach (string strFolder in arrFolders)
				{
					if (!strFolder.EndsWith(DotNetNuke.Common.Globals.glbHostSkinFolder))
					{
						arrFiles = Directory.GetFiles(strFolder, "*.ascx");
						foreach (string strFile in arrFiles)
						{
							string folder = strFolder.Substring(strFolder.LastIndexOf("\\") + 1);
							if (strLastFolder != folder)
							{
								if (!string.IsNullOrEmpty(strLastFolder))
								{
									//cboSkin.Items.Add(New ListItem(strSeparator, ""))
									SkinLst.Items.Add(GetSeparatorItem());
								}
								strLastFolder = folder;
							}
							//cboSkin.Items.Add(New ListItem(FormatSkinName(strFolder, Path.GetFileNameWithoutExtension(strFile)), "[G]" & SkinRoot & "/" & strFolder & "/" & Path.GetFileName(strFile)))
							SkinLst.Items.Add(new RadComboBoxItem(FormatSkinName(folder, Path.GetFileNameWithoutExtension(strFile)), "[G]" + SkinController.RootSkin + "/" + folder + "/" + Path.GetFileName(strFile)));
						}
					}
				}
			}

			//Set the selected item
			SkinLst.SelectedIndex = 0;
			if ((!string.IsNullOrEmpty(CurrentTab.SkinSrc)))
			{
				RadComboBoxItem selectItem = SkinLst.FindItemByValue(CurrentTab.SkinSrc);
				if (((selectItem != null)))
				{
					selectItem.Selected = true;
				}
			}
		}

		private RadComboBoxItem GetSeparatorItem()
		{
			RadComboBoxItem item = new RadComboBoxItem(GetString("SkinLstSeparator"), "");
			item.CssClass = "SkinLstSeparator";
			item.Enabled = false;
			return item;
		}

		private string FormatSkinName(string strSkinFolder, string strSkinFile)
		{
			if (strSkinFolder.ToLower() == "_default")
			{
				// host folder
				return strSkinFile;
				// portal folder
			}
			else
			{
				switch (strSkinFile.ToLower())
				{
					case "skin":
					case "container":
					case "default":
						return strSkinFolder;
					default:
						return strSkinFolder + " - " + strSkinFile;
				}
			}
		}

		private void LoadLocationList()
		{
			LocationLst.ClearSelection();
			LocationLst.Items.Clear();

			LocationLst.Items.Add(new RadComboBoxItem(GetString("NoLocationSelection"), ""));
			LocationLst.Items.Add(new RadComboBoxItem(GetString("Before"), "BEFORE"));
			LocationLst.Items.Add(new RadComboBoxItem(GetString("After"), "AFTER"));
			LocationLst.Items.Add(new RadComboBoxItem(GetString("Child"), "CHILD"));

			LocationLst.SelectedIndex = 0;
		}

		private void LoadPageList()
		{
			PageLst.ClearSelection();
			PageLst.Items.Clear();

			PageLst.DataTextField = "IndentedTabName";
			PageLst.DataValueField = "TabID";
			PageLst.DataSource = RibbonBarManager.GetPagesList();
			PageLst.DataBind();

			RadComboBoxItem disableCurrentTab = PageLst.FindItemByValue(CurrentTab.TabID.ToString());
			if (((disableCurrentTab != null)))
			{
				disableCurrentTab.Enabled = false;
			}

			PageLst.Items.Insert(0, new RadComboBoxItem(GetString("NoPageSelection"), ""));
			PageLst.SelectedIndex = 0;
		}

		private DotNetNuke.Entities.Tabs.TabInfo _CurrentTab = null;
		private DotNetNuke.Entities.Tabs.TabInfo CurrentTab
		{
			get
			{
				//Weird - but the activetab has different skin src value than getting from the db
				if (((_CurrentTab == null)))
				{
					_CurrentTab = new TabController().GetTab(PortalSettings.ActiveTab.TabID, PortalSettings.ActiveTab.PortalID, false);
				}
				return _CurrentTab;
			}
		}

		private string LocalResourceFile
		{
			get { return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType.Name); }
		}

		private string GetString(string key)
		{
			return Localization.GetString(key, LocalResourceFile);
		}

		private PortalSettings PortalSettings
		{
			get { return DotNetNuke.Entities.Portals.PortalSettings.Current; }
		}

		#endregion

	}

}


